package com.quark.common.security.handler;

import cn.hutool.json.JSONUtil;
import com.quark.common.jwt.JwtTokenManager;
import com.quark.model.system.log.SysLogDTO;
import com.quark.result.RequestResult;
import com.quark.service.system.LogService;
import com.quark.util.SysLogUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 张高昌
 * @date 2021/12/29 15:12
 * @description: 功能描述
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    private final JwtTokenManager jwtTokenManager;

    private final LogService logService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException{
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();

        String token = jwtTokenManager.generateToken(userDetails);
        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        httpServletResponse.getWriter().write(JSONUtil.toJsonStr(RequestResult.success(tokenMap)));
        //获取请求的ip地址
        String ip = getIpAddress(httpServletRequest);
        String username = authentication.getName();
        SysLogDTO sysLog = SysLogUtils.getSysLog(httpServletRequest, username);
        sysLog.setTitle(username + "用户登录");
        sysLog.setParams(username);
//        String header = httpServletRequest.getHeader(HttpHeaders.AUTHORIZATION);
//        sysLog.setServiceId(WebUtils.extractClientId(header).orElse("N/A"));
//        sysLog.setTenantId(Integer.parseInt(tenantKeyStrResolver.key()));
        logService.saveLog(sysLog);
    }



    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

}
